package com.rzjm.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.entity.dto.PickUpPlanTime;
import com.rzjm.api.entity.dto.TimeListColumns;
import com.rzjm.api.service.*;
import com.rzjm.api.util.DateUtil;
import com.rzjm.api.util.GsonResultBean;
import com.rzjm.api.util.Tools;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 *@Author: ZhouWei
 *@Description:  调查问卷相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/pick/plan")//url:模块/资源/{}/细分
public class PickUpPlanController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private UserCarListService userCarListService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private PickUpPlanService pickUpPlanService;
    @Resource
    private PickUpPlanInfoService pickUpPlanInfoService;
    @Resource
    private PickUpRecordService pickUpRecordService;
    @Resource
    private ShopService shopService;
    @Resource
    private PickUpMatterService pickUpMatterService;
    @Resource
    private CarWeeksService carWeeksService;
    @Resource
    private CarLimitTimesService carLimitTimesService;
    @Resource
    private PickUpRecordMatterService pickUpRecordMatterService;
    /**
     * 企业列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/shop/list")
    public JSONObject shopList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "pick/plan/shop/list接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int shop_type = jsonRequest.containsKey("shop_type") ? jsonRequest.getInt("shop_type") : 2;

            List<String> names = new ArrayList<>();
//            QueryWrapper<Shop> qw = new QueryWrapper<>();
//            qw.eq("state",1);
//            qw.eq("shop_type",shop_type);
            Map<String, Object> mapParam = new HashMap<>();
            mapParam.put("shop_type", 2);
            List<Shop> shopList = shopService.getListByAdminUserId(mapParam);
            if(CollUtil.isNotEmpty(shopList)){
                for (Shop shop : shopList){
                    names.add(shop.getShopName());
                }
            }
            map.put("shops",shopList);
            map.put("names",names);

//            if(shopList.size() > 0){
//                List<String> planDates = DateUtil.getAfterDateByDays(new Date(), 3);
//                List<String> planDates = DateUtil.getAfterDateByDaysExWeek(new Date(), 7, weeks);
//                List<CarWeeks> carWeeksList = carWeeksService.selectListByColumn("state", 0);
//                List<Integer> weeks = carWeeksList.stream().map(w -> w.getWeekCode()).collect(Collectors.toList());
//                map.put("dateList",planDates);

//                List<PickUpPlanTime> times = getTimes();
//                map.put("times", times);
//
//                List<TimeListColumns> timeListColumns = getTimeList();
//                map.put("timeList", timeListColumns);
//                Map<String, Object> timeMap = getCarLimitTimes();
//                map.put("times", (List<PickUpPlanTime>)timeMap.get("times"));
//                map.put("timeList", (List<TimeListColumns>)timeMap.get("limitTimesList"));

//            }

            List<String> carNames = new ArrayList<>();
            QueryWrapper<UserCarList> qwCar = new QueryWrapper<>();
            qwCar.eq("user_id",user_id);
            List<UserCarList> carLists = userCarListService.list(qwCar);
            if(CollUtil.isNotEmpty(carLists)){
                for (UserCarList carList : carLists){
                    carNames.add(carList.getCarNum());
                }
            }
            map.put("cars",carLists);
            map.put("car_names",carNames);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",shopList.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    private List<PickUpPlanTime> getTimes(){
        List<PickUpPlanTime> times = new ArrayList<>();

        String[] beginTimes = { "07:30","08:30","09:30", "10:30", "11:30", "12:30", "13:30", "14:30", "15:30","16:30","17:30", "18:30" };
        String[] endTimes = { "08:30","09:30", "10:30", "11:30", "12:30", "13:30", "14:30", "15:30","16:30","17:30", "18:30","19:30"};
        for (int i = 0 ; i < beginTimes.length; i++){
            String beginTime = beginTimes[i];
            String endTime = endTimes[i];
            PickUpPlanTime planTime = new PickUpPlanTime();
            planTime.setBeginTime(beginTime);
            planTime.setEndTime(endTime);

            times.add(planTime);
        }
        return times;
    }


    private List<TimeListColumns> getTimeList(){
        List<TimeListColumns> timeListColumns = new ArrayList<>();
        String[] beginTimes = { "07:30","08:30","0930", "10:30", "11:30", "12:30", "13:30", "14:30", "15:30","16:30","17:30", "18:30" };
        String[] endTimes = { "08:30","09:30", "10:30", "11:30", "12:30", "13:30", "14:30", "15:30","16:30","17:30", "18:30","19:30"};

        for (int i = 0 ; i < beginTimes.length; i++){

            String beginTime = beginTimes[i];
            String endTime = endTimes[i];

            TimeListColumns columns = new TimeListColumns();
            columns.setText(beginTime + " ~ " + endTime);
            columns.setDisabled(false);
            timeListColumns.add(columns);
        }
        return timeListColumns;
    }

    private Map<String, Object> getCarLimitTimes(Integer shopId){
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<CarLimitTimes> carLimitTimesQueryWrapper = new QueryWrapper<>();
        carLimitTimesQueryWrapper.eq("shop_id", shopId);
        List<CarLimitTimes> limitTimesList = carLimitTimesService.list(carLimitTimesQueryWrapper);
        List<TimeListColumns> timeListColumns = new ArrayList<>();
        List<PickUpPlanTime> times = new ArrayList<>();

//        String[] beginTimes = { "07:30","08:30","0930", "10:30", "11:30", "12:30", "13:30", "14:30", "15:30","16:30","17:30", "18:30" };
//        String[] endTimes = { "08:30","09:30", "10:30", "11:30", "12:30", "13:30", "14:30", "15:30","16:30","17:30", "18:30","19:30"};

        for (int i = 0 ; i < limitTimesList.size(); i++){

            String time = limitTimesList.get(i).getTimes();
            String[] timeArr = time.split("~");

            if (timeArr != null && timeArr.length > 1){
                String beginTime = timeArr[0];
                String endTime = timeArr[1];
                PickUpPlanTime planTime = new PickUpPlanTime();
                planTime.setBeginTime(beginTime);
                planTime.setEndTime(endTime);
                times.add(planTime);

                TimeListColumns columns = new TimeListColumns();
                columns.setText(time);
                columns.setDisabled(false);
                timeListColumns.add(columns);
            }
        }
        map.put("limitTimesList", timeListColumns);
        map.put("times", times);
        return map;
    }

    /**
     * 根据企业id 获取 时间列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/date/list")
    public JSONObject dateList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "pick/plan/shop/list接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 2;

            Shop shop = shopService.findById(shop_id);
            if(shop!=null){
//                List<String> planDates = DateUtil.getAfterDateByDays(new Date(), 3);
//                map.put("dateList",planDates);
//
//                List<PickUpPlanTime> times = getTimes();
//                map.put("times", times);
//
//                List<TimeListColumns> timeListColumns = getTimeList();
//                map.put("timeList", timeListColumns);
                QueryWrapper<CarWeeks> carWeeksQueryWrapper = new QueryWrapper<>();
//                carWeeksQueryWrapper.eq("state", 0);
                carWeeksQueryWrapper.eq("shop_id", shop_id);
                List<CarWeeks> carWeeksList = carWeeksService.list(carWeeksQueryWrapper);
                if (carWeeksList != null && carWeeksList.size() > 0){
                    List<Integer> weeks = carWeeksList.stream().filter(w -> w.getState() != null && w.getState() == 0).map(w -> w.getWeekCode()).collect(Collectors.toList());
                    Map<String, Object> planDatesMap = DateUtil.getAfterDateByDaysExWeek(new Date(), 7, weeks);
                    map.put("dateList",(List<String>)planDatesMap.get("dayStr"));
                    map.put("dateWeekList",(List<String>)planDatesMap.get("dayWeekStr"));

                    Map<String, Object> timeMap = getCarLimitTimes(shop_id);
                    map.put("times", (List<PickUpPlanTime>)timeMap.get("times"));
                    map.put("timeList", (List<TimeListColumns>)timeMap.get("limitTimesList"));
                }

            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  查询当前时间的预约情况
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/record/detail")
    public JSONObject getRecordDetail(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try{
            logBefore(logger, "pick/plan/add/record 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 0;
            //预约开始时间段
            String beginTime = jsonRequest.containsKey("begin_time") ? jsonRequest.getStr("begin_time") : "";
            //预约结束时间段
            String endTime = jsonRequest.containsKey("end_time") ? jsonRequest.getStr("end_time") : "";
            //预约结束时间段
            String beginDate = jsonRequest.containsKey("begin_date") ? jsonRequest.getStr("begin_date") : "";

            int record_type = jsonRequest.containsKey("record_type") ? jsonRequest.getInt("record_type") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(StrUtil.isEmpty(beginDate) || StrUtil.isEmpty(beginTime)|| StrUtil.isEmpty(endTime)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"日期和预约时间不能为空"),true,true);
            }

            Map<String, Object> map = new HashMap<>();
            map.put("isSelf", 0);
            map.put("pickUpCount", 0);
            QueryWrapper<PickUpRecord> qwRecord = new QueryWrapper<>();
//            qwRecord.eq("plan_info_id",plan_info_id);
            qwRecord.eq("shop_id",shop_id);
            qwRecord.eq("begin_time", beginDate + " " +beginTime);
            qwRecord.eq("end_time", beginDate + " " +endTime);
            qwRecord.eq("record_type", record_type);
            qwRecord.ne("is_cancel", 1);
            List<PickUpRecord> pickRecords = pickUpRecordService.list(qwRecord);
            if(CollUtil.isNotEmpty(pickRecords)){
                map.put("pickUpCount", pickRecords.size());
                for (PickUpRecord record : pickRecords){
                    if(record.getUserId().intValue() == user_id){
                        map.put("isSelf", 1);
                        break;
                    }
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功", map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  预约
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/add/record")
    public JSONObject addRecord(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try{
            logBefore(logger, "pick/plan/add/record 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 0;
            int plan_info_id = jsonRequest.containsKey("plan_info_id") ? jsonRequest.getInt("plan_info_id") : 0;

            int car_id = jsonRequest.containsKey("car_id") ? jsonRequest.getInt("car_id") : 0;
            String wu_liao_name = jsonRequest.containsKey("wu_liao_name") ? jsonRequest.getStr("wu_liao_name") : "";
            double weight = jsonRequest.containsKey("weight") ? jsonRequest.getDouble("weight") : 0d;
            double total_weight = jsonRequest.containsKey("total_weight") ? jsonRequest.getDouble("total_weight") : 0d;

            JSONArray jsonArray =  jsonRequest.containsKey("wuliao_list") ? jsonRequest.getJSONArray("wuliao_list") : new JSONArray();
            String beginDate = jsonRequest.containsKey("begin_date") ? jsonRequest.getStr("begin_date") : "";
            //预约开始时间段
            String beginTime = jsonRequest.containsKey("begin_time") ? jsonRequest.getStr("begin_time") : "";
            //预约结束时间段
            String endTime = jsonRequest.containsKey("end_time") ? jsonRequest.getStr("end_time") : "";

            int record_type = jsonRequest.containsKey("record_type") ? jsonRequest.getInt("record_type") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            UserCarList carList = userCarListService.findById(car_id);
            if(carList == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您车辆不存在"),true,true);
            }

            if(user_id != carList.getUserId().intValue()){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您车辆不属于你"),true,true);
            }

//            PickUpPlanInfo planInfo = pickUpPlanInfoService.findById(plan_info_id);
//            if(planInfo == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该计划时段不存在"),true,true);
//            }
//
//            if(planInfo.getState() == 1){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该计划时段已被预约"),true,true);
//            }


            QueryWrapper<PickUpRecord> qwRecordMy = new QueryWrapper<>();
            qwRecordMy.ne("is_cancel", 1);
            qwRecordMy.eq("user_id", user_id);
            qwRecordMy.eq("record_type", record_type);
            qwRecordMy.eq("shop_id",shop_id);
            qwRecordMy.eq("begin_time", beginDate + " " + beginTime);
            qwRecordMy.eq("end_time", beginDate + " " + endTime);
            qwRecordMy.last("limit 1");
            PickUpRecord pickRecordMy = pickUpRecordService.getOne(qwRecordMy);
            if(pickRecordMy != null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您已预约~"),true,true);
            }

            QueryWrapper<PickUpRecord> qwRecord = new QueryWrapper<>();
//            qwRecord.eq("plan_info_id",plan_info_id);
            qwRecord.ne("is_cancel", 1);
            qwRecord.eq("record_type",record_type);
            qwRecord.eq("shop_id",shop_id);
            qwRecord.eq("begin_time", beginDate + " " + beginTime);
            qwRecord.eq("end_time", beginDate + " " + endTime);
            qwRecord.eq("is_cancel", 0);
            long count = pickUpRecordService.count(qwRecord);
            String beginTimeStr =  beginTime.substring(0, beginTime.length() - 3);
            String endTimeStr =  endTime.substring(0, endTime.length() - 3);
            QueryWrapper<CarLimitTimes> qwLimit = new QueryWrapper<>();
            qwLimit.eq("times", beginTimeStr + "~" + endTimeStr);
            qwLimit.eq("shop_id", shop_id);
            qwLimit.last("limit 1");
            CarLimitTimes carLimitTimes = carLimitTimesService.getOne(qwLimit);
            int limitCount = carLimitTimes == null ? 0 : (carLimitTimes.getLimitCarCount() == null ? 0 :
                    carLimitTimes.getLimitCarCount().intValue());
            if(count >= limitCount){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该计划时段预约已到上限"),true,true);
            }


            PickUpRecord pickUpRecord = new PickUpRecord();
            pickUpRecord.setUserId(user_id);
            pickUpRecord.setRecordType(record_type);
            pickUpRecord.setCarNum(carList.getCarNum());
            pickUpRecord.setPhoneNum(carList.getPhoneNum());
            pickUpRecord.setRealName(carList.getRealName());
            pickUpRecord.setBeginTime(DateUtil.ConvertDateByformat(beginDate + " " + beginTime,"yyyy-MM-dd HH:mm:ss"));
            pickUpRecord.setEndTime(DateUtil.ConvertDateByformat(beginDate + " " + endTime,"yyyy-MM-dd HH:mm:ss"));
//            pickUpRecord.setPlanId(planInfo.getPlanId());
//            pickUpRecord.setPlanInfoId(planInfo.getId());
            pickUpRecord.setState(0);
            pickUpRecord.setWuLiaoName(wu_liao_name);
            pickUpRecord.setShopId(shop_id);
            pickUpRecord.setWuLiaoWeight(weight);
            pickUpRecord.setWuLiaoTotalWeight(total_weight);
            pickUpRecord.setCreateTime(new Date());
            pickUpRecord.setAppointmentTime(new Date());
            pickUpRecord.setPlanDate(beginDate);
            pickUpRecord.setMattersArray(jsonArray);
            int ret = pickUpRecordService.addRecord(user, null,pickUpRecord);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"预约成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"预约失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  取消预约
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/cancel")
    public JSONObject cancel(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try{
            logBefore(logger, "pick/plan/cancel 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            PickUpRecord record = pickUpRecordService.findById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该预约不存在"),true,true);
            }

            if(record.getUserId().intValue() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该预约不属于您"),true,true);
            }

            record.setIsCancel(1);
            record.setCancelTime(new Date());
            boolean ret = pickUpRecordService.updateById(record);
            if(ret){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "取消成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"取消失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  签到
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/sign")
    public JSONObject sign(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try{
            logBefore(logger, "pick/plan/sign 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            PickUpRecord record = pickUpRecordService.findById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该预约信息不存在"),true,true);
            }

            if(record.getState() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您已叫号成功"),true,true);
            }

            int ret = pickUpRecordService.sign(user,record);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"预约成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"预约失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  叫号
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/call")
    public JSONObject call(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try{
            logBefore(logger, "pick/plan/call 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 0;
            //是否是过号  0 - 叫号  1 - 过号
            int is_stride = jsonRequest.containsKey("is_stride") ? jsonRequest.getInt("is_stride") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            PickUpPlan plan = pickUpPlanService.getTodayPlan(shop_id);
            if(plan == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前未安排计划"),true,true);
            }

            //User user, PickUpRecord record,int isStride
            int ret = pickUpRecordService.call(user,plan, is_stride);
            if(ret > 0){
                String s = "叫号成功";
                if(is_stride == 1){
                    s = "过号成功";
                }
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,s),true,true);
            } else if(ret == -1) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无签到记录"),true,true);
            } else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"叫号失败，请重试"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  插队
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/jump")
    public JSONObject jump(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try{
            logBefore(logger, "pick/plan/call 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            PickUpRecord record = pickUpRecordService.findById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该记录不存在"),true,true);
            }

            int ret = pickUpRecordService.jump(user,record);
            if(ret > 0){
                String s = "叫号成功";
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,s),true,true);
            } else if(ret == -1) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无签到记录"),true,true);
            } else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"叫号失败，请重试"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 记录列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/my/record/list")
    public JSONObject myRecordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "pick/plan/shop/list接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int is_all = jsonRequest.containsKey("is_all") ? jsonRequest.getInt("is_all") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 0;

            int record_type = jsonRequest.containsKey("record_type") ? jsonRequest.getInt("record_type") : 0;

            Integer[] states = {0,1,2};
            QueryWrapper<PickUpRecord> qw = new QueryWrapper<>();
            User user = userService.findById(user_id);
            if (user.getSysUserId() != null && user.getSysUserId() > 0){
                List<Shop> shopList = shopService.list(new QueryWrapper<Shop>().eq("car_manager_sys_user_id", user.getSysUserId()));
                if (shopList != null && shopList.size() > 0){
                    Integer[] shopIds = shopList.stream().map(s -> s.getId()).toArray(Integer[]::new);
                    if (shopIds != null && shopIds.length > 0){
                        qw.and(wrapper -> wrapper.eq("user_id",user_id).or().in("shop_id", shopIds));
                    }else {
                        qw.eq("user_id",user_id);
                    }
                }else {
                    qw.eq("user_id",user_id);
                }
            }else {
                qw.eq("user_id",user_id);
            }
//            if(is_all == 0){
//                qw.in("state",Arrays.asList(states));
//                qw.last("limit 1");
//            }
            qw.eq("record_type", record_type);
            qw.orderByDesc("create_time");
            List<PickUpRecord> records = pickUpRecordService.getPageEntityList(qw,pageIndex,pageSize);
            if(CollUtil.isNotEmpty(records)){
                for (PickUpRecord record : records){
                    Shop shop = shopService.findById(record.getShopId());
                    if(shop!=null){
                        record.setShopName(shop.getShopName());
                    }
                    List<PickUpRecordMatter> pickUpRecordMatterList = pickUpRecordMatterService
                            .selectListByColumn("pick_up_record_id", record.getId());
                    record.setPickUpRecordMatterList(pickUpRecordMatterList);
                    record.setBeginTimeStr(DateUtil.getSimpleTime1(record.getBeginTime()));
                    record.setEndTimeStr(DateUtil.getSimpleTime1(record.getEndTime()));
                }
            }

            map.put("records",records);

            map.put("before_count",0);
            if(is_all == 0 && records.size() > 0){
                QueryWrapper<PickUpRecord> qwRecordCount = new QueryWrapper<>();
                qwRecordCount.eq("plan_id",records.get(0).getPlanId());
                qwRecordCount.eq("state",1);
                qwRecordCount.ne("user_id",user_id);
                qwRecordCount.orderByAsc("appointment_time");
                long count = pickUpRecordService.count(qwRecordCount);
                map.put("before_count",count);
            }


            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",records.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 记录列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/record/list")
    public JSONObject recordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "pick/plan/shop/list接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            //is_all = 0  用户来看列表  1 - 管理员要看所有列表
            int is_all = jsonRequest.containsKey("is_all") ? jsonRequest.getInt("is_all") : 0;


            int planId = 0;
            QueryWrapper<PickUpPlan> qwPlan = new QueryWrapper<>();
            qwPlan.eq("state",2);
            qwPlan.last("limit 1");
            qwPlan.orderByDesc("id");
            PickUpPlan plan = pickUpPlanService.getOne(qwPlan);
            if(plan != null){
                planId = plan.getId();
            }
            Integer[] states = {0,1,2};
            QueryWrapper<PickUpRecord> qw = new QueryWrapper<>();
            qw.eq("user_id",user_id);
            qw.eq("plan_id",planId);
            if(is_all == 0){
                qw.in("state",Arrays.asList(states));
                qw.last("limit 1");
            }
            qw.orderByDesc("create_time");
            List<PickUpRecord> records = pickUpRecordService.list(qw);
            if(CollUtil.isNotEmpty(records)){
                for (PickUpRecord record : records){
                    Shop shop = shopService.findById(record.getShopId());
                    if(shop!=null){
                        record.setShopName(shop.getShopName());
                    }

                    record.setBeginTimeStr(DateUtil.getSimpleTime1(record.getBeginTime()));
                    record.setEndTimeStr(DateUtil.getSimpleTime1(record.getEndTime()));
                }
            }

            map.put("records",records);

            map.put("before_count",0);
            if(records.size() > 0){

                QueryWrapper<PickUpRecord> qwMyRecord = new QueryWrapper<>();
                qwMyRecord.eq("plan_id",planId);
                qwMyRecord.eq("state",1);
                qwMyRecord.eq("user_id",user_id);
                qwMyRecord.last("limit 1");
                PickUpRecord myRecord = pickUpRecordService.getOne(qwMyRecord);

                if(is_all == 0 && myRecord != null && records.size() > 0){
                    QueryWrapper<PickUpRecord> qwRecordCount = new QueryWrapper<>();
                    qwRecordCount.eq("plan_id",planId);
                    qwRecordCount.eq("state",1);
                    qwRecordCount.ne("user_id",user_id);
                    qwRecordCount.ne("id",myRecord.getId());
                    qwRecordCount.lt("appointment_time",myRecord.getAppointmentTime());
                    long count = pickUpRecordService.count(qwRecordCount);
                    map.put("before_count",count);

                    QueryWrapper<PickUpRecord> qwRecordCall = new QueryWrapper<>();
                    qwRecordCall.eq("plan_id",planId);
                    qwRecordCall.eq("state",1);
                    qwRecordCall.eq("call_state",1);
                    qwRecordCall.orderByAsc("appointment_time");
                    PickUpRecord callRecord = pickUpRecordService.getOne(qwRecordCall);
                    map.put("callRecord",callRecord);
                }
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",records.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 叫号列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/shop/record/list")
    public JSONObject shopRecordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "pick/plan/shop/list接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;


            PickUpPlan plan = pickUpPlanService.getTodayPlan(shop_id);
            if(plan == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前未安排计划"),true,true);
            }

            QueryWrapper<PickUpRecord> qw = new QueryWrapper<>();
            qw.eq("plan_id",plan.getId());
            qw.eq("shop_id",shop_id);
            qw.eq("state",1);
            qw.orderByAsc("appointment_time");
            List<PickUpRecord> records = pickUpRecordService.list(qw);
            if(CollUtil.isNotEmpty(records)){
                for (PickUpRecord record : records){
                    Shop shop = shopService.findById(record.getShopId());
                    if(shop!=null){
                        record.setShopName(shop.getShopName());
                    }
                }
            }
            map.put("records",records);
            map.put("plan",plan);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",records.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 签到 记录列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/shop/record/history")
    public JSONObject shopRecordHistoryList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "pick/plan/shop/list接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 3;


            PickUpPlan plan = pickUpPlanService.getTodayPlan(shop_id);
            if(plan == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前未安排计划"),true,true);
            }

            QueryWrapper<PickUpRecord> qw = new QueryWrapper<>();
            qw.eq("plan_id",plan.getId());
            qw.eq("shop_id",shop_id);
            qw.eq("state",state);
            qw.orderByAsc("appointment_time");
            List<PickUpRecord> records = pickUpRecordService.list(qw);
            if(CollUtil.isNotEmpty(records)){
                for (PickUpRecord record : records){
                    Shop shop = shopService.findById(record.getShopId());
                    if(shop!=null){
                        record.setShopName(shop.getShopName());
                    }
                }
            }
            map.put("records",records);
            map.put("plan",plan);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",records.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 取消预约
     * @param
     * @throws Exception
     */
    @PostMapping(value="/my/record/cancelRecord")
    public JSONObject cancelRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "pick/plan/add/record 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int recoed_id = jsonRequest.containsKey("recoed_id") ? jsonRequest.getInt("recoed_id") : 0;
            UpdateWrapper<PickUpRecord> pickUpRecordUpdateWrapper = new UpdateWrapper<>();
            pickUpRecordUpdateWrapper.set("cancel_time", new Date());
            pickUpRecordUpdateWrapper.set("is_cancel", 1);
            pickUpRecordUpdateWrapper.eq("id", recoed_id);
            boolean ret = pickUpRecordService.update(pickUpRecordUpdateWrapper);
            if(ret){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"取消预约成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"取消预约失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

}
